using System;
using System.Collections.Generic;
using System.Text;
using CKS.EBE.API;
using CKS.EBE.WebControls;

namespace CKS.EBE.WebControls
{
    public class SearchQuery : SingleListQuery
    {
        protected static string _condition = "<Or><Contains><FieldRef Name=\"Body\" /><Value Type=\"Text\">{0}</Value></Contains><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">{0}</Value></Contains></Or>";

        public SearchQuery()
        {
            ListName = Localization.GetListName(Localization.BlogList.Posts, Web.Language);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            ViewFieldsXML += "<FieldRef Name='Body'/><FieldRef Name='NumComments'/><FieldRef Name='PublishedDate'/><FieldRef Name='PostCategory'/><FieldRef Name='FileDirRef'/><FieldRef Name='BlogTitleForUrl'/><FieldRef Name='CategoriesAsText' Nullable='True' />";

            StringBuilder sb = new StringBuilder("<Where>");

            string sQuery = Page.Request["k"];
            if (string.IsNullOrEmpty(sQuery)) return;

            string[] arTerms = sQuery.Split(' ');

            if (arTerms.Length > 1)
                AddANDCondition(sb, arTerms, 0);
            else
                sb.Append(string.Format(_condition, arTerms[0]));

            sb.Append("</Where>");

            sb.Append("<OrderBy><FieldRef Name='PublishedDate' Ascending='FALSE'/></OrderBy>");

            QueryXML = sb.ToString();
        }

        protected void AddANDCondition(StringBuilder sb, string[] arTerms, int position)
        {
            sb.Append("<And>");

            if ((position + 2) < arTerms.Length)
            {
                AddANDCondition(sb, arTerms, position + 1);
                sb.Append(string.Format(_condition, arTerms[position]));
            }
            else
            {
                sb.Append(string.Format(_condition, arTerms[position]));
                if ((position+1) < arTerms.Length) sb.Append(string.Format(_condition, arTerms[position+1]));
            }

            sb.Append("</And>");
        }
    }
}
